package cn.qy.kotlin.base

/**
 * 流程控制、语句和表达式
 */
fun main() {
    fun testIf() {
        val name = "Madrigal"
        var healthPoints = 100
        // if else 语句
        if (healthPoints > 80) {
            println("$name is in excellent condition!")
        } else {
            println("$name is in awful condition!")
        }
        // 除了 if 语句，这里也可可以用 if 条件表达式实现。 请确认仅在一个分支只包含一条语句的情况下，花括号才能省略
        healthPoints -= 30
        val healthStatus = if (healthPoints > 80) "$name is in excellent condition!" else "$name is in awful condition!"
        println(healthStatus)
    }
    testIf()

    fun testLoops() {
        // for 循环
        val cakes = listOf("carrot", "cheese", "chocolate")
        for (cake in cakes) {
            println("Yummy, it's a $cake cake!")
        }
        // while 循环 和 do-while 循环
        var cakesEaten = 0
        var cakesBaked = 0
        while (cakesEaten < 3) {
            println("Eat a Cake")
            cakesEaten++
        }
        do {
            println("Bake a Cake")
            cakesBaked++
        } while (cakesBaked < cakesEaten)
    }
    testLoops()

    // 使用 when 表达式实现同样效果
    fun testWhen() {
        fun formatHealthStatus(healthPoints: Int): String {
            return when (healthPoints) {
                100 -> "is in excellent condition!"
                in 90..99 -> "has a few scratches."
                in 75..89 -> "has some minor wounds."
                in 15..74 -> "looks pretty hurt."
                else -> "is in awful condition!"
            }
        }
        println(formatHealthStatus(1))
        println(formatHealthStatus(50))
        println(formatHealthStatus(100))

        // when 甚至连()都可以省略
        val score = 100
        val pr = when {
            score >= 90 -> println('优') //分支条件表达式单纯的布尔值
            else -> println('良')
        }
        println(pr)
    }
    testWhen()
}